## Figure K.1: Effect of Lobbying on Donations, Senate: -------------------------

## Instructions ----------------------------------------------------------------
# Step 1: Adjust DATA_DIR to where data is is located
# Step 2: Adjust OUT_DIR to where output folder is
# Step 3: Run entire script
## setup -----------------------------------------------------------------------



## setup -----------------------------------------------------------------------
# clean slate
rm(list = ls())
# Need to install to read/use PanelEstimate Objects
# devtools::install_github("insongkim/PanelMatch",ref = "se_comparison")

# # LOAD PACKAGES
# library(PanelMatch)
# library(dplyr)
# options(scipen=999)
# 
# ### SUBSETTING AND PATH
# naics_sub <- c("31", "32", "33") #### <- set industries to be analyzed
# chamber_sub <- c("senate") #### <- set chamber to be analyzed
# path <- "../data/don_lob_quarter_20210525_senate.csv" ### set path to be analyzes
# #outcome_select <- c("don_any_bin", "don_pac_bin", "don_emp_bin", "don_ceo_bin", "don_gov_bin")
# outcome_select <- c("don_any_bin")
# treatment_select <- c("lob_spon_bin", "lob_cosp_only_bin", "lob_comm_bin", "lob_any_bin")
# 
# 
# #### SET ANALYSIS PARAMETERS ######
# ## refinement_method <- "CBPS.weight" # set refinement
# refinement_method <- "mahalanobis" # set refinement
# size_match <- 10 # size of matched set
# lags_match_dv <- "1:8" # DV lags to match on. Set 8 so that cover electoral cycle 
# lags_leads <- 8 # Lags/Leads in PanelMatch. Set 8 so that cover electoral cycle 
# covariates_match <- "l_sale + l_emp" # other covariates to match on
# ## exact_match <- c("naics3", "govtrack_id") # exact matchin
# exact_match <- c("govtrack_id") # exact matchin
# outcomes <- c("don_any_bin", "don_pac_bin", "don_ceo_bin", "don_gov_bin", "don_emp_bin") # treatment variable
# outcome_names <- c("AnyDon", "PacDon", "CeoDon", "GovDon", "EmpDon") # treatment variable
# treatments <- c("lob_spon_bin", "lob_cosp_only_bin", "lob_comm_bin", "lob_any_bin")
# treatname <- c("SpLob", "CoSpLob", "CommLob", "AnyLob")
# chamber_names <- c("Senate", "House")
# 
# 
# #### CREATE A DF WITH ANALYSIS PAREMTERS ######
# specs_df <- data.frame(chamber = rep(rep(c("senate", "house"), each = 5), 4),
#                        chamber_names = rep(rep(chamber_names, each = 5), 4),
#                        treatments = rep(treatments, each = 10),
#                        treatname = rep(treatname, each = 10),
#                        outcomes = rep(outcomes, 8),
#                        outcome_names = rep(outcome_names, 8),
#                        refinement_method = rep(refinement_method, 40),
#                        size_match = rep(size_match, 40),
#                        exact_match1 = rep(exact_match[1], 40),
#                        ## exact_match2 = rep(exact_match[2], 40),
#                        covariate_match = rep(covariates_match, 40),
#                        lags_match_dv = rep(lags_match_dv, 40),
#                        stringsAsFactors = FALSE)
# 
# specs_df <- specs_df %>% filter(chamber %in% chamber_sub, outcomes %in% outcome_select) # subset by chosen chamber
# 
# # LOAD DATA, SUBSET, and keep only variables needed
# don_lob <- readr::read_csv(path)%>%
#   filter(naics2 %in% naics_sub, chamber %in% chamber_sub) %>%
#   mutate(l_sale = log(sale+1), l_emp = log(emp+1)) %>%
#   select(gvkey_govtrack_id, gvkey, govtrack_id, year, year_quarter_int, naics2, chamber, # IDs
#          lob_any_bin, lob_spon_bin, lob_cosp_only_bin, lob_comm_bin, # outcomes
#          don_any_bin, don_pac_bin, don_emp_bin, don_ceo_bin, don_gov_bin, # outcomes, reverse analysis
#          l_sale, l_emp # firm covariates
#          # majority, minority_leader, majority_leader, democrat, # politician covariates
#          # latino, african_american, female,
#          # com_chair, subcom_chair, power_com,
#          # treat_don_all, treat_don_pac, treat_don_emp, treat_don_ceo, treat_don_gov, # treatments
#          # treat_lob_all, treat_lob_spons, treat_lob_cosp, treat_lob_comm
#   ) %>% # some recodings necessary
#   mutate(gvkey_govtrack_id_numeric = as.integer(as.factor(gvkey_govtrack_id)),
#          year_quarter_int = as.integer(year_quarter_int)) #
# 
# 
# 
# # need to set as DF, if not PM breaks sometimes
# don_lob <- as.data.frame(don_lob)
# 
# 
# 
# 
# # print number of rows
# print(paste0("using dataset with ", nrow(don_lob), " rows."))
# 
# 
# 
# # start loop across all outcomes
# for (i in 1:dim(specs_df)[1]) {
#   
#   # set up the respective outcome names for plot titles
#   outcome_name <- specs_df$outcome_names[i] # change with outcome used
#   chamber_name <- specs_df$chamber_names[i] #
#   treatment_name <- specs_df$treatname[i]
#   
#   # crete covariate formulat for PanelMatch()
#   covs_formula <- paste0("~ I(lag(", specs_df$outcomes[i], ", ", lags_match_dv, ")) + ", specs_df$covariate_match[i])
#   
#   
#   
#   ##### Run Panelmatch
#   Matches.lobby <- PanelMatch(lag = lags_leads, lead = 0:lags_leads, time.id = "year_quarter_int", unit.id = "gvkey_govtrack_id_numeric",
#                               treatment = specs_df$treatments[i], match.missing = TRUE,
#                               outcome.var = specs_df$outcomes[i], qoi = "att",
#                               covs.formula = as.formula(covs_formula),
#                               ## exact.match.variables = c(specs_df$exact_match1[i], specs_df$exact_match2[i]),
#                               exact.match.variables = c(specs_df$exact_match1[i]),
#                               forbid.treatment.reversal = FALSE,
#                               restrict.control.period = lags_leads,
#                               size.match = specs_df$size_match[i],
#                               data = don_lob,
#                               refinement.method = specs_df$refinement_method[i])
#   
#   output_name <- paste0("manuf_quart_revcause_", specs_df$chamber[i], "_cbps_", 
#                         specs_df$treatname[i], "_" , specs_df$outcome_names[i])
#   
#   
#   # Save PanelMatch Object
#   save(Matches.lobby, file = paste0("../output/MSets", output_name))
#   print(paste0(i,". ", "saved **Matched Sets** object to ", "../output/MSets_", output_name))
#   gc()
#   
#   
#   # Run PanelEstimate
#   PM.lobby <- PanelEstimate(sets = Matches.lobby, data = don_lob, se.method = "analytical")
#   
#   # Save PanelEstimate Object
#   save(PM.lobby, file = paste0("../output/EstObj_", output_name))
#   print(paste0(i,". ", "saved **Panel Estimate** object to ", "../output/EstObj_", output_name))
#   gc()
#   
#   
#   #### Remove PanelMatch and PanelEstimate objects at th end of each run
#   rm(PM.lobby)
#   rm(Matches.lobby)
#   gc()
#   
#   
# }



library(PanelMatch)
DATA_DIR <- "C:/Users/js.egb/Dropbox/campaign-lobby-paper/replication_package/data/figK1"
OUT_DIR <- "C:/Users/js.egb/Dropbox/campaign-lobby-paper/replication_package/output"

file_list <- list.files(DATA_DIR) 
file_list <- file_list[which(grepl("EstimateObj", x = file_list, fixed = TRUE))]

# graph parameters
yaxis_limits <- c(-0.05, 0.05) # Y Axis
xaxis_limits <- c(0.75,8.25) # X Axis
legend_font_size <- 1.25 # Font Size of Legend (if any)
point_size <- 7 # size of points
treat <- c("Any Lobbying", "Lobby Sponsor", "Lobby Cosponsor", "Lobby Committee")
ylab <- c("Estimated Effects of Lobbying on\nProbability to Donate", "",  
          "Estimated Effects of Lobbying on\nProbability to Donate", "")

file_list_sub <- rev(file.path(DATA_DIR, file_list))[c(2,4,1,3)]

#  DV: Any Donation. Treatment: Different Lobbying Types
pdf(file = file.path(OUT_DIR, "figure_k1.pdf"), # "pm_sen_quarters_revcause_anydon.pdf"
    height = 10, width = 14)
par(font.lab = 1.8, cex.lab = 1.9, cex.axis = 1.75, mar = c(6,11,4,2),
    cex.main = 2, las=1,  mfrow = c(2,2))
for (i in 1:4) {
  load(file_list_sub[i])

  # empty plot with labels  
  plot(NA, main = paste0("Any Donation, ", treat[i]),
             ylim = yaxis_limits, xlim = xaxis_limits,
             ylab = "", xlab = "", col = "black", xaxt = "n")
  abline(h = 0, lty = 3)
  
  # add point estimates
  points(PM.lobby$estimates, col = "black", pch = 19)
  mtext(side = 1, "Quarters relative to the timing of Lobbying",
        line = 3.3, cex=1.5)
  axis(1, at = c(1:8), labels = c("t+0","t+1","t+2","t+3","t+4","t+5","t+6","t+7"))
  
  # add confidence intervals
  for (j in 1:8) {
    segments(x0 = j, 
             y0 = PM.lobby$estimates[j]-PM.lobby$standard.error[j]*1.96, 
             x1 = j, 
             y1 = PM.lobby$estimates[j]+PM.lobby$standard.error[j]*1.96, 
             col = "black", lwd = 1.5)  
  }
  
}
dev.off()


